//
//  ArticleShareSheet.m
//  Doctor
//
//  Created by 陈应平 on 24/11/2016.
//  Copyright © 2016 YX. All rights reserved.
//

#import "YXSocialSnsService.h"
#import "BGHaveLineView.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UMMobClick/MobClick.h>

@interface YXSocialSnsService ()

@property (nonatomic ,strong) UIView *shareActionSheet;
@property (nonatomic ,strong) UIView *bgView;
@property (nonatomic ,strong) void(^success)(YXShareType type);

@end

@implementation YXSocialSnsService

+ (void)shareSheetWithLink:(NSString *)shareLink shareTitleText:(NSString *)shareTitleText shareDescText:(NSString *)shareDescText shareImage:(id )shareImage shareSuccess:(void(^)(YXShareType type))success{
    YXSocialSnsService *shareSheet = [[YXSocialSnsService alloc]initWithShareLink:shareLink shareTitleText:shareTitleText shareDescText:shareDescText shareImage:shareImage controller:nil shareSuccess:success];
    [[UIApplication sharedApplication].keyWindow addSubview:shareSheet];
}

- (instancetype)initWithShareLink:(NSString *)shareLink shareTitleText:(NSString *)shareTitleText shareDescText:(NSString *)shareDescText shareImage:(id )shareImage controller:(UIViewController *)controller shareSuccess:(void(^)(YXShareType type))success
{
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:kQQAppId appSecret:kQQAppKey redirectURL:nil];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:kWeiXinAppId appSecret:kWeiXinAppSecret redirectURL:nil];
    self.shareLink = shareLink;
    self.shareTitleText = shareTitleText;
    self.shareDescText = shareDescText;
    self.success = success;
    if ([shareImage isKindOfClass:[UIImage class]]) {
        self.shareImage = shareImage;
    }else if ([shareImage isKindOfClass:[NSString class]]){
        self.shareImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:shareImage]] scale:1.0];
    }
    
    self.controller = controller;
    return [self init];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    frame = [UIApplication sharedApplication].keyWindow.frame;
    if (self = [super initWithFrame:frame]) {
        [self setupViews];
    }
    return self;
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];
    
    self.shareActionSheet.y = self.height;
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.shareActionSheet.y = self.height-kGetWidth(173);
    } completion:^(BOOL finished) {
        
    }];
}

- (void)setupViews
{
    self.bgView = [[UIView alloc] initWithFrame:self.frame];
    self.bgView.backgroundColor = [UIColor blackColor];
    self.bgView.alpha = 0.6;
    [self.bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelAction:)]];
    [self addSubview:self.bgView];
    
    self.shareActionSheet = [[UIView alloc] initWithFrame:CGRectMake(0, self.height-kGetWidth(173), kScreenWidth, kGetWidth(173))];
    self.shareActionSheet.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.shareActionSheet];
    
    UILabel *shareTitle = [[UILabel alloc] init];
    shareTitle.text = @"分享";
    shareTitle.font = kSystemFont(kGetWidth(16));
    [shareTitle sizeToFit];
    shareTitle.y = kGetWidth(kGetWidth(15));
    shareTitle.centerX = kScreenWidth/2;
    shareTitle.textColor = RGB_COLOR_WITH_0x(kBlackTextColor);
    [self.shareActionSheet addSubview:shareTitle];
    
    NSArray *shareButtonImages = @[@"share_icon_weixin",@"share_icon_pengyouquan",@"share_icon_QQ"];
    NSArray *shareButtonTitles = @[@"微信",@"朋友圈",@"QQ"];
    for (NSUInteger i = 0; i < shareButtonImages.count; i++) {
        CGFloat y = UIViewBottomY(shareTitle) + kGetWidth(15);
        CGFloat height = kGetWidth(125) - kGetWidth(30) - shareTitle.height;
        UIButton *shareBtn = [[UIButton alloc] initWithFrame:CGRectMake(i*kScreenWidth/3, y, kScreenWidth/3, height)];
        [shareBtn setTitle:shareButtonTitles[i] forState:UIControlStateNormal];
        [shareBtn setImage:[UIImage imageNamed:shareButtonImages[i]] forState:UIControlStateNormal];
        [shareBtn setTitleColor:RGB_COLOR_WITH_0x(kBlackText666Color) forState:UIControlStateNormal];
        shareBtn.titleLabel.font = kSystemFont(kGetWidth(13));
        shareBtn.tag = i+1000;
        [shareBtn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.shareActionSheet addSubview:shareBtn];
        
        // 以下是调整文字和图片位置的代码
        CGFloat imageWith = kGetWidth(37);
        CGFloat imageHeight = imageWith;
        CGSize labelSize = [shareButtonTitles[i] getStringSizeWithFont:kSystemFont(kGetWidth(13))];
        CGFloat labelWidth = labelSize.width;
        CGFloat labelHeight = labelSize.height;
        CGFloat imageOffsetX = (imageWith + labelWidth) / 2 - imageWith / 2;
         CGFloat imageOffsetY = imageHeight / 2;
        shareBtn.imageEdgeInsets = UIEdgeInsetsMake(-imageOffsetY, imageOffsetX, imageOffsetY, -imageOffsetX);
        CGFloat labelOffsetX = (imageWith + labelWidth / 2) - (imageWith + labelWidth) / 2;
        CGFloat labelOffsetY = labelHeight / 2;
        // 将文字向下移动一些
        shareBtn.titleEdgeInsets = UIEdgeInsetsMake(labelOffsetY+kGetWidth(16), -labelOffsetX, -labelOffsetY, labelOffsetX);
    }
    
    BGLineView *cancelView = [[BGLineView alloc] initWithFrame:CGRectMake(0, self.shareActionSheet.height-kGetWidth(48), kScreenWidth, kGetWidth(48)) lineType:TopLine backgroundColor:[UIColor whiteColor]];
    [self.shareActionSheet addSubview:cancelView];
    
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:cancelView.frame];
    cancelBtn.y += 1;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:RGB_COLOR_WITH_0x(kBlackTextColor) forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = kSystemFont(kGetWidth(17));
    [cancelBtn addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.shareActionSheet addSubview:cancelBtn];
}

- (void)shareBtnClick:(UIButton *)sender
{
    [MobClick endEvent:@"experience_share"];
    switch (sender.tag-1000) {
        case 0:     // 微信好友
            [self shareToWechat];
            break;
        case 1:     // 朋友圈
            [self shareToTimeLine];
            break;
        case 2:     // QQ
            [self shareToQQ];
            break;
        default:
            break;
    }
    [self.bgView removeFromSuperview];
    [self.shareActionSheet removeFromSuperview];
    
}

- (void)shareToWechat
{
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.shareTitleText descr:self.shareDescText thumImage:self.shareImage];
    shareObject.webpageUrl = [self.shareLink stringByAppendingString:@"?type=wx"];
    messageObject.shareObject = shareObject;
    __weak typeof(self) weakSelf = self;
    [[UMSocialManager defaultManager]shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self.controller completion:^(id result, NSError *error) {
        NSLog(@"%@",error);
        [weakSelf shareResults:!error type:WechatSessionType];
    }];
}

- (void)shareToTimeLine
{
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.shareDescText descr:self.shareDescText thumImage:self.shareImage];
    shareObject.webpageUrl = [self.shareLink stringByAppendingString:@"?type=wx"];
    messageObject.shareObject = shareObject;
    __weak typeof(self) weakSelf = self;
    [[UMSocialManager defaultManager]shareToPlatform:UMSocialPlatformType_WechatTimeLine messageObject:messageObject currentViewController:self.controller completion:^(id result, NSError *error) {
        NSLog(@"%@",error);
        [weakSelf shareResults:!error type:WechatTimeLineType];
    }];
}

- (void)shareToQQ
{
    DEBUG_LOG(@"分享qq");
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    NSString *title = @" ";
    if (self.shareTitleText.length) {
        title = self.shareTitleText;
    }
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:self.shareDescText thumImage:self.shareImage];
    shareObject.webpageUrl = [self.shareLink stringByAppendingString:@"?type=qq"];
    messageObject.shareObject = shareObject;
    
    __weak typeof(self) weakSelf = self;
    [[UMSocialManager defaultManager]shareToPlatform:UMSocialPlatformType_QQ messageObject:messageObject currentViewController:self.controller completion:^(id result, NSError *error) {
        NSLog(@"%@",error);
        [weakSelf shareResults:!error type:QQType];
    }];
}

- (void)shareResults:(BOOL)isSuccess type:(YXShareType)type{
    if (isSuccess) {
        if (self.success) {
            self.success(type);
        }
    }
    [self removeFromSuperview];
}

- (void)cancelAction:(UIButton *)sender
{
    self.shareActionSheet.y = self.height-kGetWidth(173);
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.shareActionSheet.y = self.height;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

@end
